package com.logservice.controller;

import com.alibaba.fastjson.JSON;
import com.sml.requset.SmlAlertRequest;
import com.sml.response.LogView;
import com.sml.util.DingDingRobotUtil;
import com.logservice.service.LogService;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author linlx
 * @Date 2021/9/5 15:46
 * @Description
 **/
@RestController
@Slf4j
public class AlertController {

  @Resource
  private LogService logService;

  @PostMapping("/cat/alert")
  public String catAlert(@RequestParam String to, @RequestParam String value,
      @RequestParam String key) {
    log.info("to = {}, value = {}, key ={}", to, value, key);

    String content = "【CAT】\n"
        + value;

    // 钉钉TOKEN请替换成自己的
    String result = DingDingRobotUtil.sendMessage(
        "https://oapi.dingtalk.com/robot/send?access_token=536c09dc79ddb596d73034822f426303437189cd1edf21dabd77a4b6a0e9bb77",
        content);
    log.info("result = {}", result);
    return "200";
  }

  @PostMapping("/sml/alert")
  public String smlAlert(@RequestBody @Validated SmlAlertRequest request) {
    log.info("request = {}", JSON.toJSON(request));
    // 防止链路上的其他服务的日志还未写入redis
    try {
      TimeUnit.SECONDS.sleep(3L);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    List<String> feignIdList = request.getFeignIdList();
    feignIdList.forEach(feignId -> {
      List<LogView> logViewList = logService.getLog(feignId);
      String content = "【SML】\n";
      // 钉钉TOKEN请替换成自己的
      DingDingRobotUtil.sendMessage(
          "https://oapi.dingtalk.com/robot/send?access_token=536c09dc79ddb596d73034822f426303437189cd1edf21dabd77a4b6a0e9bb77",
          content + JSON.toJSONString(logViewList));
    });
    return "ok";
  }
}
